// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import path, { resolve } from "path";
import fs from "fs";

import * as vscode from "vscode";
import { spawn } from "child_process";

import { uploadFile } from "./utils/qiniu-upload";

// This method is called when your extension is activated
// Your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
  const disposable = vscode.commands.registerCommand(
    "extension.paste-image-qiniu",
    () => {
      pasteImage();
    }
  );

  context.subscriptions.push(disposable);
}

// This method is called when your extension is deactivated
export function deactivate() {}

function pasteImage() {
  vscode.window.showInformationMessage("开始上传照片");
  // 获取当前编辑文件
  const editor = vscode.window.activeTextEditor;
  if (!editor) {
    return;
  }

  // 获取当前文件路径
  const fileUrl = editor.document.uri;

  if (fileUrl.scheme === "untitled") {
    vscode.window.showInformationMessage(
      "在粘贴图像之前，您需要先保存当前编辑文件。"
    );
    return;
  }

  // 获取选中光标
  const selection = editor.selection;
  // 获取选中内容
  const selectText = editor.document.getText(selection);
  if (selectText && !/^[\w\-.]+$/.test(selectText)) {
    vscode.window.showInformationMessage("您选择的文件名无效!");
  }

  // 获取插件配置信息
  const config = vscode.workspace.getConfiguration("paste-image-qiniu");
  const localPath = config["localPath"];
  if (localPath && localPath.length !== localPath.trim().length) {
    vscode.window.showErrorMessage("指定的路径无效: '" + localPath + "'");
    return;
  }

  const filePath = fileUrl.fsPath;
  const imagePath = getImagePath(filePath, selectText, localPath);

  vscode.window.setStatusBarMessage("上传图片到七牛...", 3000);
  // createImageDirectoryWithImagePath(imagePath)
  //   .then((imagePath) => {
  //     console.log(imagePath);
  saveClipboardImageToFileAndGetPath(imagePath, (imagePath: string) => {
    if (!imagePath) {
      return;
    }

    if (imagePath === "no image") {
      vscode.window.setStatusBarMessage("Done", 3000);
      vscode.window.showInformationMessage("粘贴板没有图片.");
      return;
    }

    uploadFile(config, imagePath)
      .then((result: Record<string, any>) => {
        vscode.window.showInformationMessage("上传成功");
        const img = result.url;
        editor.edit((textEditorEdit) => {
          textEditorEdit.insert(editor.selection.active, img);
        });
      })
      .catch((err) => {
        vscode.window.showErrorMessage("Upload error.");
      });
  });
  // })
  // .catch((err) => {
  //   vscode.window.showErrorMessage("Failed make folder.");
  // });
}

/**
 * 获取图片路径
 * @param filePath 文件路径
 * @param selectText 选择文字
 * @param localPath 本地路径
 * @returns
 */
function getImagePath(filePath: string, selectText: string, localPath: string) {
  let imageFileName = "";
  if (!selectText) {
    imageFileName = new Date().getTime() + ".png";
  } else {
    imageFileName = selectText + ".png";
  }

  // 图片保存路径
  const folderPath = path.dirname(filePath);
  let imagePath = "";
  if (path.isAbsolute(localPath)) {
    imagePath = path.join(localPath, imageFileName);
  } else {
    imagePath = path.join(folderPath, localPath, imageFileName);
  }
  return imagePath;
}

/**
 * 创建图片目录
 * @param imagePath
 * @returns
 */
function createImageDirectoryWithImagePath(imagePath: string) {
  return new Promise<string>((resolve, reject) => {
    const imageDirectory = path.dirname(imagePath);

    if (fs.existsSync(imageDirectory)) {
      resolve(imagePath);
    } else {
      fs.mkdir(imageDirectory, (err) => {
        if (err) {
          reject(err);
        } else {
          resolve(imagePath);
        }
      });
    }
  });
}

function saveClipboardImageToFileAndGetPath(imagePath: string, cb: Function) {
  if (!imagePath) {
    return;
  }
  let platform = process.platform;
  if (platform === "win32") {
    // Windows
    const scriptPath = path.join(__dirname, "./lib/pc.ps1");
    const powershell = spawn("powershell", [
      "-noprofile",
      "-noninteractive",
      "-nologo",
      "-sta",
      "-executionpolicy",
      "unrestricted",
      "-windowstyle",
      "hidden",
      "-file",
      scriptPath,
      imagePath,
    ]);
    powershell.on("exit", function (code, signal) {});
    powershell.stdout.on("data", function (data) {
      cb(data.toString().trim());
    });
  } else if (platform === "darwin") {
    // Mac
    let scriptPath = path.join(__dirname, "./lib/mac.applescript");
    let ascript = spawn("osascript", [scriptPath, imagePath]);
    ascript.on("exit", function (code, signal) {});
    ascript.stdout.on("data", function (data) {
      cb(data.toString().trim());
    });
  } else {
    // Linux

    let scriptPath = path.join(__dirname, "./lib/linux.sh");

    let ascript = spawn("sh", [scriptPath, imagePath]);
    ascript.on("exit", function (code, signal) {});
    ascript.stdout.on("data", function (data) {
      let result = data.toString().trim();
      if (result == "no xclip") {
        vscode.window.showInformationMessage(
          "You need to install xclip command first."
        );
        return;
      }
      cb(result);
    });
  }
}
